package serverCheck

import (
	"../../library/ecdhSev"
	"../../library/protocol"
	"../../library/response"
	"../../model"
	"bytes"
	"github.com/gogf/gf/g/crypto/gaes"
	"github.com/gogf/gf/g/frame/gmvc"
	"github.com/gogo/protobuf/proto"
)

type Controller struct {
	gmvc.Controller
}

func (c *Controller) Index() {
	response.Json(c.Request,404,"404")
}

/*用公钥加上本地的私钥共享的秘密*/
func (c *Controller) Ecdh() {
	//传过来的数据
	data := c.Request.GetRaw()
	//组装返回信息
	callBackMessage := &protocol.Company{}
	//
	if len(data) < 57 {
		c.Response.Header().Set("Content-Type",  "application/octet-stream");
		_, _ = c.Response.ResponseWriter.Write([]byte{})
		return
	}
	//公钥
	pubkey:=data[0:57]
	//内容
	cid:=string(data[57:])
	//取缓存
	server:=ecdhSev.EccKeyMap.Get(cid)
	//实例化ecdh对象
	Server := &ecdhSev.EccKey{}
	if server==nil {
		Server = ecdhSev.CreateECCKey(cid)
	}else {
		Server = server.(*ecdhSev.EccKey)
	}
	//拼凑加密证书
	md5Protocol := Server.ComputerECCKeyMD5(pubkey)
	//查询公司的信息
	companyMessage,err := model.GetCompanyMessage(cid)
	if err != nil || len(companyMessage) == 0{
		callBackMessage.Status = 0
		callBackMessage.Num = 0
		callBackMessage.InvalidTime = "0000-00-00 00:00:00"
	}else {
		callBackMessage.Status = 1
		callBackMessage.Num = companyMessage["num"].Int32()
		callBackMessage.InvalidTime = companyMessage["invalid_time"].String()
	}
	callBackMessages, _ := proto.Marshal(callBackMessage)
	d:=bytes.NewBuffer(Server.PubKey)
	dataAes,err:=gaes.Encrypt(callBackMessages,md5Protocol)
	d.Write(dataAes)
	//返回内容
	c.Response.Header().Set("Content-Type",  "application/octet-stream");
	_, _ = c.Response.ResponseWriter.Write(d.Bytes())
}
